/*
 * Project: a2
 * Copyright (C) 2008 ralfoide gmail com,
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.alfray.a2.engine;

import android.util.Log;


public abstract class BaseThread extends Thread {

    private final static boolean DEBUG = true;

    protected String mTag;
    protected boolean mContinue;
    protected boolean mIsPaused;

    public BaseThread(String name) {
        super(name);
        mTag = name;
    }

    /**
     * Starts a new thread or pause a current thread.
     */
    @Override
    public synchronized void start() {
        mContinue = true;
        mIsPaused = false;
        if (getState() == State.NEW) {
            super.start();
            if (DEBUG) Log.d(mTag, "Cold start");
        } else {
            if (DEBUG) Log.d(mTag, "Warm start (unpause)");
            notify();
        }
    }

    /**
     * Indicate thread should pause.
     * Derived classes must call {@link #pauseWait()} at the beginning or
     * their {@link #run()} loop.
     */
    public void onPause() {
        mIsPaused = true;
        if (DEBUG) Log.d(mTag, "onPause");
    }

    /**
     * If a thread has been paused, wait for the pause to be finished
     * (by a call to {@link #start()}.
     *
     * @return true if the thread was paused, in which case the caller loop
     * must check {@link #mContinue} and abort if it is set.
     */
    public synchronized boolean pauseWait() {
        if (!mIsPaused) return false;

        while(mIsPaused) {
            try {
                wait();
            } catch (InterruptedException e) {
                if (DEBUG) Log.d(mTag, "Pause wait expired: " + e.getMessage());
            }
        }

        return true;
    }

    /**
     * Tell the thread it must quit at the next iteration.
     */
    public void waitForStop() {
        try {
            synchronized(this) {
                mContinue = false;
                mIsPaused = false;
                notify();
            }
            join();
            if (DEBUG) Log.d(mTag, "Stopped");
        } catch (InterruptedException e) {
            Log.e(mTag, "Join failed", e);
        }
    }

    @Override
    public abstract void run();
}
